package com.example.demo.controller;

import com.example.common.entity.ArticleInfo;
import com.example.common.entity.UserInfo;
import com.example.common.tools.AjaxResult;
import com.example.common.tools.AppVariable;
import com.example.common.tools.ArticleInfoUtils;
import com.example.common.tools.UserSessionUtils;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CommentService;
import com.example.demo.service.LikesService;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import com.example.demo.entity.vo.ArticleInfoVO;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/art")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private LikesService likesService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    //定时发布提供锁
    private static Object lock = new Object();

    @RequestMapping("/mylist")
    public AjaxResult getArtListById(HttpServletRequest request, Integer uid) {
        UserInfo userInfo = null;
        //获取用户信息
        if(uid == null) {
            // 当前登录用户信息
            userInfo = UserSessionUtils.getUser(request);
        } else {
            userInfo = userService.getUserById(uid);
        }
        if(userInfo != null) {
            //成功获取用户信息，需要使用用户 id 获取该用户的所有文章
            //对获取到的文章正文进行字数限制
            List<ArticleInfo> articleInfoList =
                    ArticleInfoUtils.artLengthHandle(articleService.getAllArtInfoByUid(userInfo.getId()));
            return AjaxResult.success(articleInfoList);
        }
        return AjaxResult.fail(403, "参数错误");
    }

    @RequestMapping("/del")
    public AjaxResult delArt(Integer id, HttpServletRequest request) {
        if(id == null) {
            return AjaxResult.fail(403, "参数有误");
        }
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if(userInfo == null) {
            return AjaxResult.fail(403, "session参数错误!");
        }
        //根据 aid 删除评论和点赞数据
        commentService.delCommentByAid(id);
        likesService.delLikesInfoByAid(id);
        return AjaxResult.success(articleService.delArt(id, userInfo.getId()));
    }

    @RequestMapping("/detail")
    public AjaxResult getArtInfoById(Integer id) {
        if(id == null || id <= 0) {
            return AjaxResult.fail(403, "参数非法!");
        }
        //获取文章信息
        ArticleInfo articleInfo = articleService.getArtInfoById(id);
        if(articleInfo == null) {
            return AjaxResult.fail(403, "参数非法");
        }
        return AjaxResult.success(articleInfo);
    }

    @RequestMapping("incr-rcount")
    public AjaxResult incrRCount(Integer id) {
        if(id != null && id > 0) {
            return AjaxResult.success(articleService.incrRCount(id));
        }
        return AjaxResult.fail(403, "未知错误!");
    }

    @RequestMapping("/add")
    public AjaxResult add(HttpServletRequest request, ArticleInfo articleInfo) {
        //1.非空校验
        if(articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
        !StringUtils.hasLength(articleInfo.getContent())) {
            return AjaxResult.fail(403, "非法参数");
        }
        //2.得到当前登录用户(uid)
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if(userInfo == null || userInfo.getId() < 0) {
            return AjaxResult.fail(403, "参数非法!");
        }
        //3.添加数据库并返回结果
        articleInfo.setUid(userInfo.getId());
        return AjaxResult.success(articleService.add(articleInfo));
    }

    @RequestMapping("/update")
    public AjaxResult update(HttpServletRequest request, ArticleInfo articleInfo) {
        //非空校验
        if(articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
                !StringUtils.hasLength(articleInfo.getContent())){
            return AjaxResult.fail(403, "参数非法!");
        }
        //获取用户信息，防止其他用户修改另一个用户的文章
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUsername()) ||
                userInfo.getId() <= 0) {
            return AjaxResult.fail(403, "参数非法");
        }
        //校验是否未当前用户的关键信息
        articleInfo.setUid(userInfo.getId());
        articleInfo.setUpdatetime(LocalDateTime.now());
        return AjaxResult.success(200, articleService.update(articleInfo));
    }


    /**
     * 博客列表分页功能
     * @param pindex 当前页码
     * @param psize 每页显示条数(约定每页显示 3 条)
     * @return
     */
    //limit 3 offset 0
    //limit 3 offset 3
    //        offset 6
    //offset = (pindex - 1) * psize
    @RequestMapping("/listbypage")
    public AjaxResult getlistByPage(Integer pindex, Integer psize) {
        //非空校验
        if(pindex == null || pindex < 1) {
            pindex = 1;
        }
        if(psize == null || psize < AppVariable.PSIZE) {
            psize = AppVariable.PSIZE;
        }
        //公式计算得到 offset
        int offset = (pindex - 1) * psize;
        //将获取到的文章正文进行字数限制
        List<ArticleInfo> list =
                ArticleInfoUtils.artLengthHandle(articleService.getListByPage(psize, offset));
        //当前列表有多少也
        //a.总共有多少条数据
        int totalCount = articleService.getArtAllCount();
        //b.总条数 / psize
        double pcountdb = totalCount / (psize * 1.0);
        //c.使用进1法得到总页数
        int pcount = (int) Math.ceil(pcountdb);
        HashMap<String, Object> result = new HashMap<>();
        result.put("list", list);
        result.put("pcount", pcount);
        return AjaxResult.success(result);
    }

    @RequestMapping("/allcount")
    public AjaxResult getArtAllCount() {
        return AjaxResult.success(articleService.getArtAllCount());
    }

    @RequestMapping("/save")
    public AjaxResult saveArt(HttpServletRequest request, ArticleInfo articleInfo) {
        //1.非空校验
        if(articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
        !StringUtils.hasLength(articleInfo.getContent())) {
            return AjaxResult.fail(403, "参数错误!");
        }
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUsername()) ||
                !StringUtils.hasLength(userInfo.getPassword())) {
            return AjaxResult.fail(403, "参数错误");
        }
        //设置 uid
        articleInfo.setUid(userInfo.getId());
        //保存文章草稿
        return AjaxResult.success(articleService.saveArt(articleInfo));
    }

    @RequestMapping("/draft-list")
    public AjaxResult getMyDraftListByUid(HttpServletRequest request) {
        //获取 session 用户信息
        UserInfo userInfo = UserSessionUtils.getUser(request);
        //非空校验
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUsername()) ||
        !StringUtils.hasLength(userInfo.getPassword())) {
            return AjaxResult.fail(403, "参数错误!");
        }
        return AjaxResult.success(articleService.getMyDraftListByUid(userInfo.getId()));
    }

    @RequestMapping("/draft-save")
    public AjaxResult saveDraft(ArticleInfo articleInfo) {
        //非空校验
        if(articleInfo == null || !StringUtils.hasLength(articleInfo.getTitle()) ||
        !StringUtils.hasLength(articleInfo.getContent())) {
            return AjaxResult.fail(403, "参数错误!");
        }
        //修改保存草稿时间
        articleInfo.setUpdatetime(LocalDateTime.now());
        //修改文章
        return AjaxResult.success(articleService.saveDraft(articleInfo));
    }

    @RequestMapping("/timeadd")
    public AjaxResult timeAdd(HttpServletRequest request, ArticleInfoVO articleInfoVO) {
        //非空校验
        if(articleInfoVO == null || !StringUtils.hasLength(articleInfoVO.getTitle()) ||
        !StringUtils.hasLength(articleInfoVO.getContent())) {
            return AjaxResult.fail(403, "参数错误!");
        }
        UserInfo userInfo = UserSessionUtils.getUser(request);
        if(userInfo == null || !StringUtils.hasLength(userInfo.getUsername()) ||
        !StringUtils.hasLength(userInfo.getPassword())) {
            return AjaxResult.fail(403, "参数错误");
        }
        //设置定时发布，启动一个线程，每两秒询问一次是否到达过期时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //使用线程池，避免频繁的创建和销毁线程
        AppVariable.threadPool.submit(new Runnable() {
            @Override
            public void run() {
                synchronized (lock) {
                    while(true) {
                        if(ArticleInfoUtils.checkOvertime(sdf.format(System.currentTimeMillis()),
                                articleInfoVO.getPostTime())) {
                            //到达过期时间
                            ArticleInfo articleInfo = new ArticleInfo();
                            articleInfo.setTitle(articleInfoVO.getTitle());
                            articleInfo.setContent(articleInfoVO.getContent());
                            articleInfo.setUid(userInfo.getId());
                            //添加文章
                            articleService.add(articleInfo);
                            break;
                        }
                        try {
                            System.out.println("休眠2s");
                            lock.wait(2000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        //发布博客
        return AjaxResult.success(userInfo.getId());
    }

}
